package com.keosimage.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import weibo4j.http.AccessToken;
import weibo4j.util.WeiboConfig;

public class KeosImageOauthFilter extends HttpServlet implements Filter {

	private static final long serialVersionUID = 7942073170499493801L;
	static Logger log = Logger.getLogger(KeosImageOauthFilter.class.getName());

	@Override
	public void destroy() {
	}

	public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) sRequest;
		HttpServletResponse response = (HttpServletResponse) sResponse;
		HttpSession session = request.getSession();
		String actionPath = request.getServletPath();
		if (actionPath.equals("")) {
			actionPath += "/";
		}
		if ((actionPath.startsWith("/")
				&& actionPath.endsWith(".action")
				&& !actionPath.startsWith("/keos/index") && !actionPath
					.startsWith("/index"))
				&& !actionPath.startsWith("/keos/oauth_callback")) {

			AccessToken accessToken = (AccessToken) session
					.getAttribute(KeosImageConstants.ACCESS_TOKEN);
			if (accessToken == null) {
				StringBuffer url = new StringBuffer(WeiboConfig.getValue(
						"authorizeURL").trim());
				url.append("?client_id="
						+ WeiboConfig.getValue("client_ID").trim());
				url.append("&redirect_uri="
						+ WeiboConfig.getValue("redirect_URI").trim());
				url.append("&response_type="
						+ WeiboConfig.getValue("response_type").trim());

				String userAgent = request.getHeader("User-Agent");
				if (isSmartPhone(userAgent)) {
					url.append("&display="
							+ WeiboConfig.getValue("display").trim());
				}
				log.debug(url.toString());
				response.sendRedirect(url.toString());
				return;
			}
		}
		filterChain.doFilter(sRequest, sResponse);
	}

	private boolean isSmartPhone(String useragent) {
		String[] keywords = { "Android", "iPhone", "iPod", "iPad",
				"Windows Phone", "MQQBrowser" };
		if (!useragent.contains("Windows NT")
				|| (useragent.contains("Windows NT") && useragent
						.contains("compatible; MSIE 9.0;"))) {
			// 排除 苹果桌面系统
			if (!useragent.contains("Windows NT")
					&& !useragent.contains("Macintosh")) {
				for (String item : keywords) {
					if (useragent.contains(item)) {
						return true;
					}
				}
			}
		}
		return false;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
}
